<?php
namespace app\api\controller;

use app\common\service\HttpService;
use lib\phpqrcode\QRcode;
use think\App;
use app\common\model\OrderModel;

/**  YSF
 *   支付管理
 *   Date: 2018/12/19
 * Class Pay
 * @package app\api\controller
 */
class Pay extends Base
{
    protected $orderModel;

    // 初始化构造方法
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->orderModel = new OrderModel();
    }


    /**
     *   支付宝当面付--扫码付款
     * @throws \Exception
     */
    public function alipay()
    {
        require_once __DIR__.'/../../../extend/alipay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
        require_once  __DIR__.'/../../../extend/alipay/f2fpay/service/AlipayTradeService.php';

        // 接收参数-- 判断参数
        if (empty($this->parm['order_id'])) {
            returnJson(0, '缺少参数');
        }

        $order_id = $this->parm['order_id'] ?? '';

        // 查询订单信息
        $where['order_id'] = $order_id;
        $order_data = $this->orderModel->getOne($where);
        if (!$order_data) {
            returnJson(-1000, '下单失败');
        }

        // 获取配置文件
        $config = $this->api_config['alipay'];

        // 回调地址
        $config['notify_url'] = HttpService::getDomain().'/'.$config['notify_url'];
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = trim($order_data['order_sn']);
        // 订单名称，必填
        $subject = trim($order_data['meal_name']);
        // 付款金额，必填
        $total_amount = trim(0.01);
        // 商品描述，可空
        $body = trim($order_data['meal_name']);
        // 支付超时，线下扫码交易定义为5分钟
        $timeExpress = "5m";
        // 构造参数

        $qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($out_trade_no);
        $qrPayRequestBuilder->setTotalAmount($total_amount);
        $qrPayRequestBuilder->setTimeExpress($timeExpress);
        $qrPayRequestBuilder->setSubject($subject);
        $qrPayRequestBuilder->setBody($body);

        // 调用qrPay方法获取当面付应答
        $qrPay = new \AlipayTradeService($config);
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);

        //	根据状态值进行业务处理
        switch ($qrPayResult->getTradeStatus()) {
            case "SUCCESS":
                $response = $qrPayResult->getResponse();
                // 生成二维码
                $qr = $this->getCode($response->qr_code, $order_data['order_sn'], 'aliqrcode');
                if ($qr) {
                    $data['order_id'] = $order_id;
                    $data['code_url'] = HttpService::getDomain().'/'.$qr;
                    $data['order_sn'] = $order_data['order_sn'];
                    $data['pay_money'] = formatMoney($order_data['order_has_pay_money']);
                    returnJson(1, 'ok', $data);
                } else {
                    returnJson(0, '支付宝创建订单二维码失败!');
                }
                break;
            case "FAILED":
                returnJson(0, '支付宝创建订单二维码失败!');
                break;
            case "UNKNOWN":
                returnJson(0, '系统异常，状态未知');
                break;
            default:
                returnJson(0, '系统异常，状态未知');
                break;
        }
    }

    /**
     *   支付宝支付状态--查询
     * @throws \Exception
     */
    public function alipayStatus()
    {
        require_once __DIR__.'/../../../extend/alipay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
        require_once  __DIR__.'/../../../extend/alipay/f2fpay/service/AlipayTradeService.php';

        // 接收参数-- 判断参数
        if (empty($this->parm['order_sn'])) {
            returnJson(0, '缺少参数');
        }
        $order_sn = $this->parm['order_sn'] ?? '';

        // 获取配置信息
        $config = $this->api_config['alipay'];
        // 获取商户订单号
        $out_trade_no = trim($order_sn);
        // 构造查询业务请求参数对象

        $queryContentBuilder = new \AlipayTradePrecreateContentBuilder();
        $queryContentBuilder->setOutTradeNo($out_trade_no);
        // 初始化类对象，调用queryTradeResult方法获取查询应答
        $queryResponse = new \AlipayTradeService($config);
        $queryResult = $queryResponse->queryTradeResult($queryContentBuilder);
        // 根据查询返回结果状态进行业务处理
        switch ($queryResult->getTradeStatus()){
            case "SUCCESS":
                $response = $queryResult->getResponse();
                if($response->code==10000 && $response->trade_status == 'TRADE_SUCCESS'){
                    returnJson(0, '支付成功');
                }
                break;
            case "FAILED":
                returnJson(1, '支付宝查询交易失败或者交易已关闭!!!');
                break;
            case "UNKNOWN":
                returnJson(1, '系统异常，订单状态未知!!!');
                break;
            default:
                returnJson(1, '不支持的查询状态，交易返回异常!!!');
                break;
        }
    }

    /**
     *   生成二维码
     * @param $url         链接url
     * @param $order_sn    订单编号
     * @param string $dir  目录
     * @param bool $logo   logo
     * @return string
     */
    public function getCode($url, $order_sn, $dir = 'aliqrcode', $logo = false)
    {
        require_once "../extend/lib/phpqrcode/phpqrcode.php"; // 引入url生成二维码

        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;           //生成图片大小
        //生成二维码图片
        $date = date('Ymd') . '/';
        $path = './uploads/'.$dir.'/';
        file_exists($path) || mkdir($path, 0777);
        $file = $order_sn . '.png';
        $filename = $path . $file;
        QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        $logo = $logo; //准备好的logo图片
        $QR = $filename; //已经生成的原始二维码图
        $QR = imagecreatefromstring(file_get_contents($QR));
        if ($logo !== false) {
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR); //二维码图片宽度
            $QR_height = imagesy($QR); //二维码图片高度
            $logo_width = imagesx($logo); //logo图片宽度
            $logo_height = imagesy($logo); //logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        }

        //输出图片
        imagepng($QR, $filename);
        $filename = trim($filename, '.');
        return $filename;
    }



}